import { createDiscreteApi } from "naive-ui";

// 用户信息
export const useUser = () => useState("user", () => null);

// 赋值用户信息给user
export async function useRefreshUserInfo() {
  const token = useCookie("token");
  const user = useUser();
  if (token.value) {
    const { data, error } = await useGetinfoApi();
    if (data.value) {
      user.value = data.value;
    }
  }
}

// 退出登录
export async function useLogout() {
  await useLogoutApi();

  const user = useUser();
  if (user.value) {
    user.value = null;
  }

  const token = useCookie("token");
  if (token) {
    token.value = null;
  }

  const { message } = createDiscreteApi(["message"]);
  message.success("退出成功");
  const route = useRoute();
  if (route.path !== "/") {
    navigateTo("/", { replace: true });
  }
}

//限定用户登录且绑定手机号才能进行操作
export function useHasAuth(callback = null) {
  const route = useRoute();
  const user = useUser();
  const token = useCookie("token");
  const { message } = createDiscreteApi(["message"]);

  if (!token.value) {
    message.error("请先登录");
    // return navigateTo({
    //   name: "login",
    //   query: {
    //     redirect: encodeURIComponent(route.fullPath),
    //   },
    // });
    return navigateTo("/login?from=" + route.fullPath);
  }

  const phone = user.value?.phone;
  if (!phone && route.name !== "bindphone") {
    message.error("请先绑定手机号");
    // return navigateTo("/bindphone?redirect=" + route.query.redirect);
    return navigateTo("/bindphone?from=" + route.fullPath);
  }

  if (callback && typeof callback === "function") {
    callback();
  }
}

//点赞/取消点赞公共方法
export function useHandleSupportPost() {
  const supportLoading = ref(false);

  const handleSupport = (item) => {
    //用户登录才能操作
    useHasAuth(async () => {
      //行为判断
      let type = item.issupport ? "unsupport" : "support";
      let msg = item.issupport ? "取消点赞" : "点赞";

      supportLoading.value = true;
      const { error } = await usePostSupportApi(item.id, type);
      supportLoading.value = false;

      //操作失败
      if (error.value) return;

      //操作成功
      if (type === "unsupport") {
        item.support_count--;
      } else {
        item.support_count++;
      }
      item.issupport = !item.issupport;

      const { message } = createDiscreteApi(["message"]);
      message.success(msg + "成功！");
    });
  };

  return {
    supportLoading,
    handleSupport,
  };
}
